﻿using BTL_Cloud.Core.Extensions;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TL_Cloud.Core.Entities;
using TL_Cloud.Core.Services;
using TL_Cloud.Models.BookShop;
using TL_Cloud.RepositoryInterface.BookShop;
using TL_Cloud.ViewModels.BookShop.BaseClass;

namespace TL_Cloud.RepositoryService.BookShop
{
    public class BaseClassRepostiory : BaseRepository,IBaseClassRepository
    {
        public BaseClassRepostiory(AppBookShopContext myContext,
          IPropertyMappingContainer propertyMappingContainer) : base(myContext, propertyMappingContainer)
        {
        }

        public async Task<PaginatedList<Base_ClassInfo>> GetAllEntitiesAsync(BaseClassQueryParameters parameters)
        {
            var query = _myContext.BaseClassInfo.AsQueryable();

            if (!string.IsNullOrEmpty(parameters.keyWord))
            {
                string keyword = parameters.keyWord.ToLowerInvariant();
                query=query.Where(n => n.ClassName.ToLowerInvariant().Contains(keyword));
            }

            query = query.ApplySort(parameters.OrderBy, _propertyMappingContainer.Resolve<BaseClassResource, Base_ClassInfo>());
            List<Base_ClassInfo> data;
            int count = 0;           
            if (parameters.isPage)
            {
                count = await query.CountAsync();
                data = await query
                  .Skip(parameters.PageIndex * parameters.PageSize)
                  .Take(parameters.PageSize)
                  .ToListAsync();
            }
            else
            {
                data = await query.ToListAsync();
            }
            return new PaginatedList<Base_ClassInfo>(parameters.PageIndex, parameters.PageSize, count, data);
        }

        public async Task<Base_ClassInfo> GetEntityByIdAsync(string id)
        {
            return await _myContext.BaseClassInfo.FindAsync(id);
        }

        public void Add(Base_ClassInfo entity)
        {
            _myContext.BaseClassInfo.Add(entity);
        }

        public void Delete(Base_ClassInfo entity)
        {
            _myContext.BaseClassInfo.Remove(entity);
        }

        public void Update(Base_ClassInfo entity)
        {
            _myContext.Entry(entity).State = EntityState.Modified;
        }

    }
}
